import email
import poplib
from email.parser import Parser

class EMailClient:
    '''Email Client class'''
    def __init__(self, host, port, username, userpass):
        self.host = host
        self.port = port
        self.username = username
        self.userpass = userpass

    def __del__(self):
        if self.M != None:
            self.M.quit()

    def auth(self):
        if self.port == 995:
            self.M = poplib.POP3_SSL(self.host, self.port)
        else:
            self.M = poplib.POP3(self.host, self.port)

        self.M.user(self.username)
        self.M.pass_(self.userpass)

        return self.M.getwelcome()

    def retrive(self, count=0):
        try:
            self.count = self.M.stat()[0]
        except poplib.error_proto:
            raise("Error")

        if self.count == 0:
            return 0
        else:
            if count < self.count:
                self.count = count
            self.mails = [self.M.top(i + 1, 0) for i in range(self.count)]

        if self.mails != None:
            return len(self.mails)
        else:
            return 0
